package shunfeng_interface

import (
	"database/sql"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"net/http"
	"time"
)

type StartRequetStruct struct {
	TransitDepotNo string `json:"transitDepotNo"` //场地代码
	TaskNo         string `json:"taskNo"`         //任务编号
	CrateNo        string `json:"crateNo"`        //板箱号
}
type StartErrResStruct struct {
	ErrorCode    string `json:"errorCode"`
	ErrorMessage string `json:"errorMessage"`
	Success      bool   `json:"success"`
}
type StartSuccessResStruct struct {
	Success bool `json:"success"`
	Obj     bool `json:"obj"`
}

type Serve struct {
	db         *sql.DB
	ip         string
	port       int
	waitSecond int //等待task和work状态变化的最长时间
}

func NewServe(ip string, port int, db *sql.DB, waitSecond int) *Serve {
	s := Serve{db: db, ip: ip, port: port, waitSecond: waitSecond}
	return &s
}

// Start 接口处理
func (s *Serve) Start(c *gin.Context) {
	//获取请求参数
	req := StartRequetStruct{}
	c.BindJSON(&req)
	log.WithFields(log.Fields{"TransitDepotNo": req.TransitDepotNo, "TaskNo": req.TaskNo, "CrateNo": req.CrateNo}).Info("start")

	errRes := StartErrResStruct{
		Success: false,
	}
	//参数缺失处理
	if req.TransitDepotNo == "" {
		errRes.ErrorCode = "001"
		errRes.ErrorMessage = "transitDepotNo 参数不能为空"
	} else if req.TaskNo == "" {
		errRes.ErrorCode = "002"
		errRes.ErrorMessage = "TaskNo 参数不能为空"
	} else if req.CrateNo == "" {
		errRes.ErrorCode = "003"
		errRes.ErrorMessage = "CrateNo 参数不能为空"
	}
	if errRes.ErrorCode != "" {
		c.JSON(http.StatusOK, errRes)
		return
	}
	//判断该taskNo是否存在
	isExist, err := s.CheckTaskNo(req.TaskNo)
	if err != nil {
		errRes.ErrorCode = "004"
		errRes.ErrorMessage = "数据库错误:" + err.Error()
		c.JSON(http.StatusOK, errRes)
		return
	} else if isExist == true {
		errRes.ErrorCode = "005"
		errRes.ErrorMessage = "该taskNo已经存在"
		c.JSON(http.StatusOK, errRes)
		return
	}

	//写入数据库
	_, err = s.InsertTask(req)
	if err != nil {
		errRes.ErrorCode = "006"
		errRes.ErrorMessage = "数据库错误:" + err.Error()
		c.JSON(http.StatusOK, errRes)
		return
	}

	//等待检测系统切换状态
	second := 0.0
	for {
		time.Sleep(500 * time.Millisecond)
		second += 0.5
		workState, _ := s.GetWorkState(req.TaskNo)
		if workState == "Working" {
			c.JSON(http.StatusOK, StartSuccessResStruct{Success: true, Obj: true})
			break
		} else if int(second) > s.waitSecond {
			errRes.ErrorCode = "007"
			errRes.ErrorMessage = "检测系统启动超时"
			c.JSON(http.StatusOK, errRes)
			break
		}
	}
}

type StopRequestStruct struct {
	TaskNo string `json:"taskNo"` //任务编号
}
type StopErrResStruct struct {
	ErrorCode    string `json:"errorCode"`
	ErrorMessage string `json:"errorMessage"`
	Success      bool   `json:"success"`
}
type StopObj struct {
	ActualLength float32  `json:"actualLength"`
	ActualWidth  float32  `json:"actualWidth"`
	ActualHeight float32  `json:"actualHeight"`
	PicUrls      []string `json:"picUrls"`
	VideoPath    string   `json:"videoPath"`
}
type StopSuccessResStruct struct {
	Success bool    `json:"success"`
	Obj     StopObj `json:"obj"`
}

// Stop 接口处理
func (s *Serve) Stop(c *gin.Context) {
	//获取请求参数
	req := StopRequestStruct{}
	c.BindJSON(&req)
	log.WithFields(log.Fields{"TaskNo": req.TaskNo}).Info("stop")

	errRes := StopErrResStruct{
		Success: false,
	}
	//参数缺失处理
	if req.TaskNo == "" {
		errRes.ErrorCode = "001"
		errRes.ErrorMessage = "TaskNo 参数不能为空"
		return
	}

	//判断该taskNo是否存在
	isExist, err := s.CheckTaskNo(req.TaskNo)
	if err != nil {
		errRes.ErrorCode = "002"
		errRes.ErrorMessage = "数据库错误:" + err.Error()
		c.JSON(http.StatusOK, errRes)
		return
	} else if isExist == false {
		errRes.ErrorCode = "003"
		errRes.ErrorMessage = "该taskNo不存在"
		c.JSON(http.StatusOK, errRes)
		return
	}

	//设置作业状态为停止状态
	err = s.SetTaskState(req.TaskNo, "Stop")
	if err != nil {
		errRes.ErrorCode = "004"
		errRes.ErrorMessage = "数据库设置状态错误:" + err.Error()
		return
	}

	//等待检测系统切换为完成状态
	second := 0.0
	for {
		time.Sleep(500 * time.Millisecond)
		second += 0.5
		workState, _ := s.GetWorkState(req.TaskNo)
		if workState == "Ended" {
			break
		} else if int(second) > s.waitSecond {
			errRes.ErrorCode = "005"
			errRes.ErrorMessage = "检测系统停止超时"
			c.JSON(http.StatusOK, errRes)
			return
		}
	}
	//返回数据
	obj, err := s.GetRecordByTaskNo(req.TaskNo)
	if err != nil {
		errRes.ErrorCode = "006"
		errRes.ErrorMessage = "获取该taskNo的记录失败:" + err.Error()
		c.JSON(http.StatusOK, errRes)
		return
	}
	c.JSON(http.StatusOK, StopSuccessResStruct{Success: true, Obj: obj})
}
